/* Copyright (c) 2024 Huawei Technologies Co., Ltd.
* This file is a part of the CANN Open Software.
* Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
* Please refer to the License for details. You may not use this file except in compliance with the License.
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
* See LICENSE in the root of the software repository for the full text of the License.
* ===================================================================================================================*/

#include "graph/attribute_group/attr_group_serialize.h"
#include "proto/attr_group_base.pb.h"
#include "ge_common/debug/ge_log.h"
#include "serialization/attr_serializer_registry.h"
#include "ge_common/util.h"
#include "checker.h"

namespace ge {
graphStatus AttrGroupSerialize::OtherGroupSerialize(AttrGroupsDef &attr_groups, const AttrStore &attr_store) {
  auto other_group = attr_groups.mutable_other_group_def();
  if (other_group == nullptr) {
    GELOGE(GRAPH_FAILED, "Failed to alloc proto memory to serial other group.");
    return GRAPH_FAILED;
  }

  const auto &keys_to_attrs = attr_store.FastGetAllAttrsFromOtherGroup();
  for (const auto &item : keys_to_attrs) {
    const AnyValue attr_value = item.second;
    const auto value_serializer = AttrSerializerRegistry::GetInstance().GetSerializer(attr_value.GetValueTypeId());
    GE_CHECK_NOTNULL(value_serializer);
    proto::AttrDef attr_def;
    GE_ASSERT_SUCCESS(value_serializer->Serialize(attr_value, attr_def));
    auto attr = other_group->mutable_attr();
    (*attr)[item.first] = attr_def;
  }

  return GRAPH_SUCCESS;
}

graphStatus AttrGroupSerialize::OtherGroupDeserialize(const AttrGroupsDef &attr_groups, AttrStore &attr_store) {
  auto other_group = attr_groups.other_group_def();
  for (const auto &attr : other_group.attr()) {
    const auto deserializer = AttrSerializerRegistry::GetInstance().GetDeserializer(attr.second.value_case());
    GE_CHECK_NOTNULL(deserializer);
    AnyValue attr_value;
    GE_ASSERT_SUCCESS(deserializer->Deserialize(attr.second, attr_value));
    attr_store.SetAttrToOtherGroup(attr.first, attr_value);
  }

  return GRAPH_SUCCESS;
}

}